import CustomTextArea from '@/components/antd-comp/input/CustomTextArea'
import CustomRadioGroup from '@/components/antd-comp/radio/CustomRadioGroup'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/bs-ui/accordion'
import { ButtonNumber } from '@/components/bs-ui/button'
import { InputList } from '@/components/bs-ui/input'
import { Label } from '@/components/ui/label'
import { useAssistantStore } from '@/store/assistantStore'
import { useDictStore } from '@/store/dictStore'
import { Tooltip as AntdTooltip, Radio } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import '../css/styles.css'
import IndivduationDiaIcon from './IndivduationDIaIcon'
import IndividuationDia from './IndividuationDia'
import KnowledgeDia from './KnowledgeDia'
import ModelSelect from './ModelSelect'
import PluginDia from './PluginDia'
import Temperature from './Temperature'
import WorkFlowDia from './WorkFlowDia'

export default function Setting({ propsRef2, propsRef }) {
  const { t } = useTranslation()
  const { assistantState, dispatchAssistant } = useAssistantStore()
  /* 个性化配置 */
  const [individuation, setIndividuation] = useState(false)
  /* 知识库 */
  const [knowledgeOpen, setKnowledgeOpen] = useState(false)
  const [workflowOpen, setWorkflowOpen] = useState(false)
  /* 插件 */
  const [pluginOpen, setPluginOpen] = useState(false)

  /* 新增 */
  const addFile = data => {
    const list = [...assistantState.knowledge_list, data]
    dispatchAssistant('setting', { knowledge_list: list })
  }
  const addWorkFlow = data => {
    const list = [...assistantState.flow_list, data]
    dispatchAssistant('setting', { flow_list: list })
  }
  const linkToCreate = (path, type) => {
    window.open(path, '_blank', 'noreferrer')
  }
  const { loadDictOptions } = useDictStore()
  const typeMap = useRef({})

  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then(res => {
      if (res) {
        res.unshift({
          id: 0,
          label: '全部类型',
          value: 'all'
        })
        const typeInfo = {}
        res.forEach(type => {
          typeInfo[type.id] = type.label
        })
        typeMap.current = typeInfo
      }
    })
  }

  const handleTypeInfo = val => {
    return typeMap.current[val] || '--'
  }
  useEffect(() => {
    loadTypeList()
  }, [])
  return (
    <div id="skill-scroll" className="h-full w-[50%] overflow-y-auto bg-[#F5F7FB] scrollbar-hide">
      <h1 className="settingTitle indent-4 leading-8">{t('build.basicConfiguration')}</h1>
      <Accordion type="multiple" className="w-full" ref={propsRef2}>
        {/* 基础配置 */}
        <AccordionItem value="item-1">
          <AccordionTrigger>
            <span className="moduleName">{t('build.modelConfiguration')}</span>
          </AccordionTrigger>
          <AccordionContent className="py-2">
            <div className="applicationEditPage_setting_case mb-4">
              <label htmlFor="model" className="moduleContName">
                {t('build.model')}
              </label>
              <ModelSelect
                value={assistantState.model_name}
                onChange={val => dispatchAssistant('setting', { model_name: val })}
              />
            </div>
            <div className="applicationEditPage_setting_case mb-4">
              <label htmlFor="slider" className="moduleContName">
                <div className="flexRowStart">
                  {t('build.temperature')}
                  <AntdTooltip
                    placement="top"
                    title={'用于控制生成结果的随机性和创造性，数值越高，生成回答越随机、多样'}
                    arrow={true}
                  >
                    <div className="cursonCase individuation_iconCase">
                      <IndivduationDiaIcon></IndivduationDiaIcon>
                    </div>
                  </AntdTooltip>
                </div>
              </label>
              <Temperature
                value={assistantState.temperature}
                onChange={val => dispatchAssistant('setting', { temperature: val })}
              ></Temperature>
            </div>
          </AccordionContent>
        </AccordionItem>
        {/* 开场引导 */}
        <AccordionItem value="item-2">
          <AccordionTrigger>
            <span className="moduleName">{t('build.openingIntroduction')}</span>
          </AccordionTrigger>
          <AccordionContent className="py-2">
            <div className="applicationEditPage_setting_case mb-4">
              <label htmlFor="open" className="moduleContName">
                {t('build.openingStatement')}
              </label>
              <CustomTextArea
                name="open"
                className="mt-2 min-h-[34px]"
                style={{ height: '56px' }}
                placeholder={
                  '助手将在每次对话开始时发送次信息，支持Markdown格式。开场白示例：你好，我是智能助手。我会尽我所能帮助你，请随时告诉我你的问题。'
                }
                value={assistantState.guide_word}
                onChange={e => dispatchAssistant('setting', { guide_word: e.target.value })}
              ></CustomTextArea>
              {assistantState.guide_word.length > 1000 && (
                <p className="bisheng-tip mt-1">{t('build.maximumPromptLength')}</p>
              )}
            </div>
            <div className="applicationEditPage_setting_case mb-4">
              <label htmlFor="open" className="moduleContName flexRowStart gap-1">
                {t('build.guidingQuestions')}
                <AntdTooltip placement="top" title={'为用户提供推荐问题，引导用户提问，上限 10个问题'} arrow={true}>
                  <div className="cursonCase individuation_iconCase">
                    <IndivduationDiaIcon></IndivduationDiaIcon>
                  </div>
                </AntdTooltip>
              </label>
              <InputList
                rules={[{ maxLength: 50, message: t('build.maxCharacters50') }]}
                value={assistantState.guide_question}
                onChange={list => {
                  dispatchAssistant('setting', { guide_question: list })
                }}
                placeholder={t('build.enterGuidingQuestions')}
              ></InputList>
            </div>
          </AccordionContent>
        </AccordionItem>
        {/* 回复风格 */}
        <AccordionItem value="item-3">
          <AccordionTrigger>
            <div className="flexRowStart">
              <span className="moduleName">回复风格</span>
              <AntdTooltip placement="top" title={'大模型根据不同的回复风格回答用户的问题'} arrow={true}>
                <div className="cursonCase individuation_iconCase">
                  <IndivduationDiaIcon></IndivduationDiaIcon>
                </div>
              </AntdTooltip>
            </div>
          </AccordionTrigger>
          <AccordionContent className="py-2">
            <div className="applicationEditPage_setting_case mb-4">
              <CustomRadioGroup
                className="applicationEditPage_setting_group"
                options={[
                  { label: '常规', value: 1 },
                  { label: '商务职场', value: 2 },
                  { label: '活泼开朗', value: 3 },
                  { label: '幽默诙谐', value: 4 }
                ]}
                defaultValue={assistantState.reply_style || 1}
                onChange={e => {
                  dispatchAssistant('setting', { reply_style: e })
                }}
              ></CustomRadioGroup>
            </div>
          </AccordionContent>
        </AccordionItem>
      </Accordion>
      <div className="flexCol" ref={propsRef}>
        <h1 className="settingTitle indent-4 leading-8">{t('build.knowledge')}</h1>
        <Accordion type="multiple" className="w-full ">
          {/* 知识库 */}
          <AccordionItem value="item-1">
            <AccordionTrigger>
              <div className="flex flex-1 items-center justify-between">
                <div className="flexRowStart">
                  <span className="moduleName">{t('build.knowledgeBase')}</span>
                  <AntdTooltip
                    placement="top"
                    title={'添加知识库后，智能体可根据知识库中的文件内容回答用户的问题'}
                    arrow={true}
                  >
                    <div className="cursonCase individuation_iconCase">
                      <IndivduationDiaIcon></IndivduationDiaIcon>
                    </div>
                  </AntdTooltip>
                </div>

                {/* 个性化配置 */}
                <div className="flexRowStart" onClick={e => e.stopPropagation()}>
                  <svg
                    width="14"
                    className="mr-2 text-primary hover:text-primary/80"
                    height="14"
                    viewBox="0 0 14 14"
                    onClick={() => {
                      setKnowledgeOpen(true)
                    }}
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M7 2L7 12"
                      stroke="#5964F3"
                      strokeWidth="1.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                    <path
                      d="M2 7L12 7"
                      stroke="#5964F3"
                      strokeWidth="1.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </div>
                {/* <Popover>
              <PopoverTrigger asChild className="group">
                  <Button variant="link" size="sm"><TriangleRightIcon className="group-data-[state=open]:rotate-90" /> {t('build.autoCall')}</Button>
              </PopoverTrigger>
              <PopoverContent className="w-[560px]">
                  <div className="flex justify-between">
                      <label htmlFor="model" className="bisheng-label">{t('build.callingMethod')}</label>
                      <div>
                          <RadioCard checked={false} title={t('build.autoCall')} description={t('build.autoCallDescription')} calssName="mb-4"></RadioCard>
                          <RadioCard checked title={t('build.onDemandCall')} description={t('build.onDemandCallDescription')} calssName="mt-4"></RadioCard>
                      </div>
                  </div>
              </PopoverContent>
          </Popover> */}
              </div>
            </AccordionTrigger>
            <AccordionContent className="pb-2 pt-0">
              <div className="flexCol mb-4 px-[12px] py-[0]">
                {assistantState.knowledge_list.map((item: any) => (
                  <div
                    key={item.id}
                    onClick={() => {
                      linkToCreate(`/filelib/${item.id}`, 'create')
                    }}
                    className="applicationEditPage_setting_individuationCase group flex cursor-pointer items-center justify-between"
                  >
                    <div className="flex items-center gap-2">
                      <img src={item.icon} style={{ width: '28px', height: '28px', borderRadius: '6px' }} alt="" />
                      <p className="text-sm">{item.name}</p>
                      {/* click事件？？？点击判断？？ */}
                      {/* <p className={`text-sm ${item.name && 'text-gray-300'}`}>
                        {item.name}
                        {item.name && '（权限已失效）'}
                      </p> */}
                    </div>
                    <svg
                      className="applicationEditPage_setting_individuationCase_svg"
                      onClick={event => {
                        event.stopPropagation()
                        dispatchAssistant('setting', {
                          knowledge_list: assistantState.knowledge_list.filter(t => t.id !== item.id)
                        })
                      }}
                      width="16"
                      height="16"
                      viewBox="0 0 16 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M4 5V12C4 12.5523 4.44772 13 5 13H11C11.5523 13 12 12.5523 12 12V5"
                        stroke="#7587A5"
                        strokeLinecap="round"
                      />
                      <path d="M3 5H13" stroke="#7587A5" strokeLinecap="round" />
                      <path
                        d="M6 5V4C6 3.44772 6.44772 3 7 3H9C9.55228 3 10 3.44772 10 4V5"
                        stroke="#7587A5"
                        strokeLinecap="round"
                      />
                    </svg>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
        <h1 className="settingTitle indent-4 leading-8">{t('build.abilities')}</h1>
        <Accordion
          type="multiple"
          className="w-full"
          onValueChange={e => e.includes('skill') && document.getElementById('skill-scroll').scrollTo({ top: 9999 })}
        >
          {/* 插件 */}
          {/* <AccordionItem value="item-1">
            <AccordionTrigger>
              <div className="flex flex-1 items-center justify-between">
                <span className="moduleName flexRowStart">
                  {t('build.tools')}
                  <AntdTooltip
                    placement="top"
                    title={'添加插件可以调用外部API，使智能体具备更多的能力，扩展使用场景，例如查询信息、解读内容等'}
                    arrow={true}
                  >
                    <div className="cursonCase individuation_iconCase">
                      <IndivduationDiaIcon></IndivduationDiaIcon>
                    </div>
                  </AntdTooltip>
                </span>
                <svg
                  width="14"
                  className="mr-2 text-primary hover:text-primary/80"
                  height="14"
                  viewBox="0 0 14 14"
                  onClick={e => {
                    e.stopPropagation()
                    setPluginOpen(true)
                  }}
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M7 2L7 12" stroke="#5964F3" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M2 7L12 7" stroke="#5964F3" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
            </AccordionTrigger>
            <AccordionContent className="pb-2 pt-0">
              <div className="flexCol mb-4 px-[12px] py-[0]">
                {assistantState.tool_list.map(tool => (
                  <div
                    key={tool.id}
                    className="applicationEditPage_setting_individuationCase group flex cursor-pointer items-center justify-between"
                  >
                    <div className="flex items-center gap-2">
                      <TitleIconBg id={tool.id} className="h-7 w-7">
                        <ToolIcon />
                      </TitleIconBg>
                      <p className="text-sm">{tool.name}</p>
                    </div>
                    <svg
                      className="applicationEditPage_setting_individuationCase_svg"
                      onClick={() =>
                        dispatchAssistant('setting', {
                          tool_list: assistantState.tool_list.filter(t => t.id !== tool.id)
                        })
                      }
                      width="16"
                      height="16"
                      viewBox="0 0 16 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M4 5V12C4 12.5523 4.44772 13 5 13H11C11.5523 13 12 12.5523 12 12V5"
                        stroke="#7587A5"
                        strokeLinecap="round"
                      />
                      <path d="M3 5H13" stroke="#7587A5" strokeLinecap="round" />
                      <path
                        d="M6 5V4C6 3.44772 6.44772 3 7 3H9C9.55228 3 10 3.44772 10 4V5"
                        stroke="#7587A5"
                        strokeLinecap="round"
                      />
                    </svg>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem> */}
          {/* 工作流 */}
          {<AccordionItem value="skill">
            <AccordionTrigger>
              <div className="flex flex-1 items-center justify-between">
                <span className="moduleName flexRowStart">
                  工作流
                  <AntdTooltip
                    placement="top"
                    title={'通过可视化界面实现复杂和稳定的业务流程编排，例如项目计划和报告分析'}
                    arrow={true}
                  >
                    <div className="cursonCase individuation_iconCase">
                      <IndivduationDiaIcon></IndivduationDiaIcon>
                    </div>
                  </AntdTooltip>
                </span>
                <svg
                  width="14"
                  className="mr-2 text-primary hover:text-primary/80"
                  height="14"
                  viewBox="0 0 14 14"
                  onClick={e => {
                    e.stopPropagation()
                    setWorkflowOpen(true)
                  }}
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M7 2L7 12" stroke="#5964F3" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M2 7L12 7" stroke="#5964F3" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
            </AccordionTrigger>
            <AccordionContent className="pb-2 pt-0">
              <div className="flexCol mb-4" style={{ padding: '0 12px' }}>
                {assistantState.flow_list.map((item: any) => (
                  <div
                    key={item.id}
                    onClick={() => {
                      linkToCreate(`/workflow/${item.id}`, 'create')
                    }}
                    className="applicationEditPage_setting_individuationCase group flex cursor-pointer items-center justify-between"
                  >
                    <div className="flex items-center gap-2">
                      <img src={item.logo} style={{ width: '28px', height: '28px', borderRadius: '6px' }} alt="" />
                      <p className="text-sm">{item.name}</p>
                    </div>
                    <svg
                      className="applicationEditPage_setting_individuationCase_svg"
                      onClick={event => {
                        event.stopPropagation()
                        dispatchAssistant('setting', {
                          flow_list: assistantState.flow_list.filter(t => t.id !== item.id)
                        })
                      }}
                      width="16"
                      height="16"
                      viewBox="0 0 16 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M4 5V12C4 12.5523 4.44772 13 5 13H11C11.5523 13 12 12.5523 12 12V5"
                        stroke="#7587A5"
                        strokeLinecap="round"
                      />
                      <path d="M3 5H13" stroke="#7587A5" strokeLinecap="round" />
                      <path
                        d="M6 5V4C6 3.44772 6.44772 3 7 3H9C9.55228 3 10 3.44772 10 4V5"
                        stroke="#7587A5"
                        strokeLinecap="round"
                      />
                    </svg>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>}
          {/* 短期记忆 */}
          <AccordionItem value="memory">
            <AccordionTrigger>
              <span className="moduleName flexRowStart">
                {t('application.appliCallSettingEndMemory')}
                <AntdTooltip placement="top" title={'可记录用户与智能体会话过程中的短期记忆内容'} arrow={true}>
                  <div className="cursonCase individuation_iconCase">
                    <IndivduationDiaIcon></IndivduationDiaIcon>
                  </div>
                </AntdTooltip>
              </span>
            </AccordionTrigger>
            <AccordionContent className="py-2">
              <div className=" applicationEditPage_setting_case mb-4">
                <Radio.Group
                  onChange={val => {
                    dispatchAssistant('setting', { remember_mode: val.target.value })
                  }}
                  value={assistantState.remember_mode}
                  className="applicationEdit_memoryBox"
                >
                  <Radio value={0} className="applicationEdit_memory">
                    <div className="flexRowStart">
                      <Label htmlFor="r1">{t('application.appliCallSettingEnd')}</Label>
                      <div style={{ margin: '0 4px' }}>
                        <ButtonNumber
                          value={assistantState.remember_last_num}
                          onChange={val => dispatchAssistant('setting', { remember_last_num: val })}
                          max={5}
                          min={1}
                          step={1}
                        />
                      </div>
                      <Label htmlFor="r1">轮</Label>
                    </div>
                  </Radio>
                  <Radio value={1}>
                    <div className="flexRowStart">
                      <Label htmlFor="r2">{t('application.appliCallSettingEnd')}</Label>
                      <div style={{ margin: '0 4px' }}>
                        <ButtonNumber
                          value={assistantState.remember_last_minute}
                          onChange={val => dispatchAssistant('setting', { remember_last_minute: val })}
                          max={60}
                          min={1}
                          step={1}
                        />
                      </div>
                      <Label htmlFor="r2">{t('application.appliCallSettingEndTime')}</Label>
                    </div>
                  </Radio>
                </Radio.Group>

                {/* <MemoryTemp value={assistantState.temperature} onChange={val => dispatchAssistant('setting', { temperature: val })}></MemoryTemp> */}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* 个性化配置 */}
      {individuation && (
        <IndividuationDia
          indivduationClose={() => {
            setIndividuation(false)
          }}
          indivduationSubmit={() => {
            setIndividuation(false)
            console.log('保存？？？')
          }}
        ></IndividuationDia>
      )}

      {/* 知识库弹窗 */}
      {knowledgeOpen && (
        <KnowledgeDia
          knowledge_list={assistantState.knowledge_list}
          addFile={addFile}
          open={knowledgeOpen}
          setOpen={setKnowledgeOpen}
        ></KnowledgeDia>
      )}

      {/* 插件弹窗  */}
      {pluginOpen && (
        <PluginDia
          open={pluginOpen}
          setOpen={setPluginOpen}
          select={assistantState.tool_list}
          onSelect={tool => {
            dispatchAssistant('setting', {
              tool_list: [...assistantState.tool_list, tool]
            })
          }}
        ></PluginDia>
      )}

      {/* 工作流弹窗 */}
      {workflowOpen && (
        <WorkFlowDia
          flow_list={assistantState.flow_list || []}
          addWorkFlow={addWorkFlow}
          open={workflowOpen}
          setOpen={setWorkflowOpen}
        ></WorkFlowDia>
      )}
    </div>
  )
}
